package ru.reaperoq.inventory.components.textField

import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.CalendarMonth
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.KeyboardType
import formatTime
import toLong

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DateTextField(
    label: String, startDate: Long? = null, onChange: (Long) -> Unit
) {
    val regex = "^(0[1-9]|[12][0-9]|3[01])\\.(0[1-9]|1[012])\\.\\d{4}\$".toRegex()
    var isVisible by remember { mutableStateOf(false) }
    val datePickerState = rememberDatePickerState(
        initialSelectedDateMillis = startDate
    )
    var currentText by remember {
        mutableStateOf(startDate?.let { formatTime(it, "dd.MM.yyyy") } ?: "")
    }
    val isValid = remember(currentText) { regex.matches(currentText) || currentText.isEmpty() }
    if (isVisible) {
        DatePickerDialog(onDismissRequest = { isVisible = false }, dismissButton = {
            TextButton(onClick = {
                isVisible = false
            }) {
                Text("Отмена")
            }
        }, confirmButton = {
            TextButton(onClick = {
                datePickerState.selectedDateMillis?.let {
                    currentText = formatTime(it, "dd.MM.yyyy")
                    onChange(it)
                }
                isVisible = false
            }) {
                Text("ОК")
            }
        }) {
            DatePicker(state = datePickerState)
        }
    }
    OutlinedTextField(
        modifier = Modifier.fillMaxWidth(),
        value = currentText,
        onValueChange = {
            currentText = it
            try {
                if (regex.matches(it)) {
                    onChange(it.toLong("dd.MM.yyyy"))
                }
            } catch (_: Exception) {
            }
        },
        trailingIcon = {
            IconButton(onClick = { isVisible = true }) {
                Icon(
                    imageVector = Icons.Outlined.CalendarMonth,
                    contentDescription = null
                )
            }
        },
        supportingText = {
            if (!isValid) {
                Text("Дата должна быть в формате дд.ММ.гггг")
            }
        },
        keyboardOptions = KeyboardOptions(
            keyboardType = KeyboardType.Number
        ),
        isError = !isValid,
        label = { Text(text = label) },
        singleLine = true
    )
}